//
//  TradeDetailView.m
//  DaDaBao
//
//  Created by admin on 15/8/26.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "TradeDetailView.h"
#import "TradeModel.h"
@interface TradeDetailView()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView * recordTableView;
@property (nonatomic,strong)NSMutableArray *listDataArray;
@property (nonatomic,assign)int idx;
@property (nonatomic,strong)NSString *url;
@property(nonatomic,strong)UIButton *noDataBt;
@property(nonatomic,strong)UIButton *tipBt;
@property (nonatomic,assign) int n;
@end
@implementation TradeDetailView
- (void)getHttpData
{
    [MBProgressHUD showHUDAddedTo:self animated:TRUE];
    _noDataBt.hidden = TRUE;
    _tipBt.hidden = TRUE;
    _n++;
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1], @"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]};
    [AppGlobalClass PostDataWithNSstring:self.url withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [_recordTableView.header endRefreshing];
            [_recordTableView.footer setState:MJRefreshStateIdle];
            [_recordTableView.footer endRefreshing];

            if(_idx == 0)
            {
                [_listDataArray removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray objectAtIndex:0];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    TradeModel *model = [[TradeModel alloc]initWithDictionary:[listArray objectAtIndex:i]];
                    [_listDataArray addObject:model];
                }
                
                _idx++;

                if(listArray.count < 10)
                {
                    [_recordTableView.footer noticeNoMoreData];
                }
               else {
                    if (_n<2) {
                        _recordTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                    }

                }
                [_recordTableView reloadData];        

            }
            else
            {
                if (self.listDataArray.count==0) {
                    _noDataBt.hidden = FALSE;
                    
                }
                
                [self.recordTableView.footer noticeNoMoreData];
            }
        }
        [MBProgressHUD hideAllHUDsForView:self animated:TRUE];

    } failure:^(NSError *error){
        
        _noDataBt.hidden = FALSE;
        [_listDataArray removeAllObjects];
        [_recordTableView reloadData];
        
        [_recordTableView.header endRefreshing];
        [_recordTableView.footer setState:MJRefreshStateIdle];
        [_recordTableView.footer endRefreshing];

        [MBProgressHUD hideAllHUDsForView:self animated:TRUE];
    } networkerror:^(NSString *networkerror){
        
        [self.listDataArray removeAllObjects];
        [self.recordTableView reloadData];
        
        [_recordTableView.header endRefreshing];
        [_recordTableView.footer setState:MJRefreshStateIdle];
        [_recordTableView.footer endRefreshing];
        
        _tipBt.hidden = FALSE;
        
        [MBProgressHUD hideAllHUDsForView:self animated:TRUE];
    }];
}
-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 180.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt setBackgroundImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

- (UIButton *)noDataBt
{
    if (!_noDataBt) {
        _noDataBt = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 180.0f) / 2.0f, 116.0f, 130.0f)];
        [_noDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        _noDataBt.hidden = TRUE;
    }
    return _noDataBt;
}

- (void)buttonAgainTapped:(id)sender
{
    [_recordTableView.header beginRefreshing];
}

-(id)initWithFrame:(CGRect)frame withUrl:(NSString *)url nameWithArray:(NSArray *)arr
{
    if (self = [super initWithFrame:frame])
    {
        _url = url;
        _listDataArray = [[NSMutableArray alloc]init];
        //创建表头目录
        UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40*HSCALE)];
        headView.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
        [self addSubview:headView];
        
        UILabel * userLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        userLabel.center = CGPointMake(SCREEN_WIDTH/6, 20*HSCALE);
        userLabel.text = [arr objectAtIndex:0];
        userLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:userLabel];
        
        UILabel * investMoneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        investMoneyLabel.center = CGPointMake(SCREEN_WIDTH/2, 20*HSCALE);
        investMoneyLabel.text =[arr objectAtIndex:1];
        investMoneyLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:investMoneyLabel];
        
        UILabel * investTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        investTimeLabel.center = CGPointMake(SCREEN_WIDTH*5/6, 20*HSCALE);
        investTimeLabel.text = [arr objectAtIndex:2];;
        investTimeLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:investTimeLabel];
        
        //创建表
        _recordTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40*HSCALE, SCREEN_WIDTH, SCREEN_HEIGHT - 64.0f - 40*HSCALE) style:UITableViewStylePlain];
        _recordTableView.delegate = self;
        _recordTableView.dataSource = self;
        _recordTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        __weak __typeof(self) weakSelf = self;
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        _recordTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheTableView];
        }];
        
             [_recordTableView.header beginRefreshing];//开始刷新
        _recordTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];//设置当数据不多的时候，下面无cell
        [self addSubview:_recordTableView];
        
        [_recordTableView addSubview:self.tipBt];
        [_recordTableView addSubview:self.noDataBt];
    }
    return self;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_listDataArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f*HSCALE;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:TRUE];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"a";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        
        UILabel * statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        statusLabel.center = CGPointMake(SCREEN_WIDTH/6, 20*HSCALE);
        statusLabel.textAlignment = NSTextAlignmentCenter;
        statusLabel.tag = 100;
        [cell.contentView addSubview:statusLabel];
        
        UILabel * investMoneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        investMoneyLabel.center = CGPointMake(SCREEN_WIDTH/2, 20*HSCALE);
        investMoneyLabel.textAlignment = NSTextAlignmentCenter;
        investMoneyLabel.tag = 101;
        [cell.contentView addSubview:investMoneyLabel];
        
        UILabel * investTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/3, 40*HSCALE)];
        investTimeLabel.numberOfLines = 0;
        investTimeLabel.center = CGPointMake(SCREEN_WIDTH*5/6 - 10.0f, 20*HSCALE);
        investTimeLabel.textAlignment = NSTextAlignmentRight;
        investTimeLabel.tag = 102;
        [cell.contentView addSubview:investTimeLabel];
        
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 45.5f, SCREEN_WIDTH, 0.5f)];
        sepLab.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:sepLab];

    }
    
    TradeModel *model = [_listDataArray objectAtIndex:indexPath.row];
    
    UILabel * statusLabel = (UILabel *)[cell.contentView viewWithTag:100];
//    赋值
    statusLabel.text = model.status;
    
    UILabel * investMoneyLabel = (UILabel *)[cell.contentView viewWithTag:101];
//   赋值
    investMoneyLabel.text = [NSString stringWithFormat:@"%@元",model.money];
    
    UILabel * investTimeLabel = (UILabel *)[cell.contentView viewWithTag:102];
//   赋值
    investTimeLabel.text = [[model.createTime componentsSeparatedByString:@" "] firstObject];
    
    return cell;
}
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
